Wprowadzenie

W poniższych przykładach zakładamy, że znasz już podstawowe informacje z zakresu wyszukiwania elementów DOM.

classList

Parametr classList zawiera zestaw metod, które pozwalają na operacje na klasach danego elementu.

Metoda Zastosowanie
add dodanie klasy
remove usunięcie klasy
toggle dodanie klasy jeśli jej nie było, i vice versa
contains sprawdzenie czy element zawiera daną klasę

Przykłady:

const div = document.querySelector('#testing-div');

div.classList.add('active');
console.log(div.classList.contains('active')); // true

div.classList.remove('active');
console.log(div.classList.contains('active')); // false

div.classList.toggle('active');
console.log(div.classList.contains('active')); // true

innerHTML

const div = document.querySelector('#testing-div');

console.log(div.innerHTML);

div.innerHTML = '<strong>Hello world!</strong>';

insertAdjacentHTML

Metoda insertAdjacentHTML służy do wstawiania kodu HTML bez usuwania zawartości danego elementu. Jako pierwszy argument podaje się tekst, który decyduje o miejscu wstawienia kodu HTML.

Argument Miejsce wstawienia kodu
`'beforebegin' przed elementem
'afterbegin' w elemencie, na początku jego zawartości
'beforeend' w elemencie, na końcu jego zawartości
'afterend' po elemencie

Składnia:

const div = document.querySelector('#testing-div');
const newCode = '<strong>Hello world!</strong>';

div.insertAdjacentHTML('beforeend', newCode);

insertAdjacentElement

Ta metoda działa analogicznie do metody insertAdjacentHTML. Różni się tylko tym, że drugim argumentem będzie element DOM, a nie kod HTML.

Składnia:

const div = document.querySelector('#testing-div');

const newLink = document.createElement('a');
newLink.setAttribute('href', 'https://kodilla.com');
newLink.innerHTML = "Kodilla";

div.insertAdjacentHTML('beforeend', newLink);

createElement

Tworzenie nowego elementu DOM można osiągnąć za pomocą metody createElement wykonanej na obiekcie document. Element zostanie jedynie stworzony i zwrócony – nie zostanie dodany na stronie.

Składnia:

const newDiv = document.createElement('div');

remove

Usunięcie elementu z DOM można wykonać za pomocą metody remove wykonanej na elemencie, który ma zostać usunięty.

const galleryDiv = document.querySelector('div.gallery');
galleryDiv.remove();